package com.ldu.exam.service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ldu.exam.assistant.BeanAssistant;
import com.ldu.exam.dao.TestPaperRepository;
import com.ldu.exam.dao.TestQuestionRepository;
import com.ldu.exam.model.TestPaperModel;
import com.ldu.exam.model.TestQuestionModel;

@Service
public class TestPaperService {
	@Autowired TestPaperRepository repository;
	@Autowired TestQuestionRepository testQuestionRepository;
	
	public Page<TestPaperModel> findAll(Pageable page)
	{
		return this.repository.findAll(page);
	}
	
	public TestPaperModel add(TestPaperModel model)
	{
		return this.repository.save(model);
	}
	
	@Transactional
	public Object putQuestions(String id , Set<TestQuestionModel> questions)
	{
		this.testQuestionRepository.removeRelquestions(id);
		
		Set<TestQuestionModel> set = questions.stream().map(x->{
			TestQuestionModel model = this.testQuestionRepository.findById( x.getId()).orElse(null);
			
			if(null != model)
				model.getPapers().add(TestPaperModel.builder().id(id).build()) ;
			
			return model;
		}) .collect(Collectors.toSet());
		TestPaperModel tpm = this.repository.findById(id).orElse(null);
		int i = 0 ;
		String content = "";
		for (TestQuestionModel testQuestionModel : set) {
			i += Integer.parseInt(testQuestionModel.getQuestionScore());
			content += testQuestionModel.getContent()+"    ";
		}
		tpm.setAllScore(String.valueOf(i));
		tpm.setContent(content);
		this.repository.save(tpm);
		return this.testQuestionRepository.saveAll( set);
	}
	
	public void delete(String id) {
		TestPaperModel model = new TestPaperModel();
		model.setId(id);
		this.repository.delete(model);
	}
	
	public Object update(String id,TestPaperModel model)
	{
		model.setId(null);
		TestPaperModel origin = this.repository.findById(id).orElse(null);
		String [] nullPropertyNameStrings = BeanAssistant.getNullPropertyNames(model);
		BeanUtils.copyProperties(model, origin, nullPropertyNameStrings);
		return this.repository.save(origin);
	}
	
	public Page<TestPaperModel> findByNameContaining( String name , Pageable page)
	{
		return this.repository.findByNameContaining(name, page);
	}
	
	public List<TestPaperModel> findNoPage()
	{
		return this.repository.findAll();
	}
}
